import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../models/login_request.dart';
import '../widgets/auth_text_field.dart';
import '../widgets/auth_button.dart';
import '../widgets/loading_overlay.dart';
import '../utils/validators.dart';
import '../utils/auth_guard.dart';

class RegisterScreen extends StatefulWidget {
  const RegisterScreen({super.key});

  @override
  State<RegisterScreen> createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen>
    with SingleTickerProviderStateMixin {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  final _displayNameController = TextEditingController();
  final _partnerNameController = TextEditingController();
  DateTime? _relationshipStartDate;
  
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.0, 0.6, curve: Curves.easeOut),
    ));
    
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.2, 1.0, curve: Curves.easeOut),
    ));
    
    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _usernameController.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    _displayNameController.dispose();
    _partnerNameController.dispose();
    super.dispose();
  }

  Future<void> _handleRegister() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    final authProvider = context.read<AuthProvider>();
    final registerRequest = RegisterRequest(
      username: _usernameController.text.trim(),
      email: _emailController.text.trim(),
      password: _passwordController.text,
      confirmPassword: _confirmPasswordController.text,
      displayName: _displayNameController.text.trim().isEmpty 
          ? null 
          : _displayNameController.text.trim(),
      partnerName: _partnerNameController.text.trim().isEmpty 
          ? null 
          : _partnerNameController.text.trim(),
      relationshipStartDate: _relationshipStartDate,
    );

    final success = await authProvider.register(registerRequest);

    if (mounted) {
      if (success) {
        // 注册成功，显示成功消息并跳转
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('注册成功！正在为您登录...'),
            backgroundColor: Colors.green.shade600,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
          ),
        );
        
        // 延迟一下让用户看到成功消息
        await Future.delayed(const Duration(milliseconds: 1500));
        
        // 调用路由守卫处理跳转
        print('✅ 注册成功，等待路由跳转...');
        await RouteGuard.handleLoginSuccess(context);
      } else {
        // 显示错误信息
        final error = authProvider.error;
        if (error != null) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(error),
              backgroundColor: Colors.red.shade600,
              behavior: SnackBarBehavior.floating,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
              ),
            ),
          );
        }
      }
    }
  }

  Future<void> _selectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _relationshipStartDate ?? DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: Theme.of(context).colorScheme.copyWith(
              primary: const Color(0xFFFF6B9D),
            ),
          ),
          child: child!,
        );
      },
    );
    
    if (picked != null && picked != _relationshipStartDate) {
      setState(() {
        _relationshipStartDate = picked;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AuthProvider>(
      builder: (context, authProvider, child) {
        return LoadingOverlay(
          isLoading: authProvider.isLoading,
          message: '正在注册...',
          child: Scaffold(
            backgroundColor: const Color(0xFFF9FAFB),
            appBar: AppBar(
              backgroundColor: Colors.transparent,
              elevation: 0,
              leading: IconButton(
                icon: const Icon(
                  Icons.arrow_back_ios,
                  color: Color(0xFF1F2937),
                ),
                onPressed: () => Navigator.pop(context),
              ),
              title: const Text(
                '创建账号',
                style: TextStyle(
                  color: Color(0xFF1F2937),
                  fontWeight: FontWeight.w600,
                ),
              ),
              centerTitle: true,
            ),
            body: SafeArea(
              child: LayoutBuilder(
                builder: (context, constraints) {
                  final isWideScreen = constraints.maxWidth > 600;
                  final maxWidth = isWideScreen ? 400.0 : double.infinity;
                  
                  return Center(
                    child: Container(
                      constraints: BoxConstraints(maxWidth: maxWidth),
                      padding: const EdgeInsets.symmetric(horizontal: 24),
                      child: SingleChildScrollView(
                        child: AnimatedBuilder(
                          animation: _animationController,
                          builder: (context, child) {
                            return FadeTransition(
                              opacity: _fadeAnimation,
                              child: SlideTransition(
                                position: _slideAnimation,
                                child: Form(
                                  key: _formKey,
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.stretch,
                                    children: [
                                      const SizedBox(height: 20),
                                      
                                      // 用户名
                                      AuthTextField(
                                        label: '用户名',
                                        controller: _usernameController,
                                        prefixIcon: Icons.person_outline,
                                        validator: Validators.username,
                                        autofocus: true,
                                      ),
                                      
                                      const SizedBox(height: 20),
                                      
                                      // 邮箱
                                      AuthTextField(
                                        label: '邮箱地址',
                                        controller: _emailController,
                                        prefixIcon: Icons.email_outlined,
                                        keyboardType: TextInputType.emailAddress,
                                        validator: Validators.email,
                                      ),
                                      
                                      const SizedBox(height: 20),
                                      
                                      // 密码
                                      AuthTextField(
                                        label: '密码',
                                        controller: _passwordController,
                                        prefixIcon: Icons.lock_outline,
                                        isPassword: true,
                                        validator: Validators.password,
                                      ),
                                      
                                      const SizedBox(height: 20),
                                      
                                      // 确认密码
                                      AuthTextField(
                                        label: '确认密码',
                                        controller: _confirmPasswordController,
                                        prefixIcon: Icons.lock_outline,
                                        isPassword: true,
                                        validator: (value) => Validators.confirmPassword(
                                          value,
                                          _passwordController.text,
                                        ),
                                      ),
                                      
                                      const SizedBox(height: 24),
                                      
                                      // 分隔线
                                      Row(
                                        children: [
                                          Expanded(
                                            child: Divider(
                                              color: Colors.grey.shade300,
                                              thickness: 1,
                                            ),
                                          ),
                                          Padding(
                                            padding: const EdgeInsets.symmetric(horizontal: 16),
                                            child: Text(
                                              '可选信息',
                                              style: TextStyle(
                                                fontSize: 14,
                                                color: Colors.grey.shade600,
                                                fontWeight: FontWeight.w500,
                                              ),
                                            ),
                                          ),
                                          Expanded(
                                            child: Divider(
                                              color: Colors.grey.shade300,
                                              thickness: 1,
                                            ),
                                          ),
                                        ],
                                      ),
                                      
                                      const SizedBox(height: 24),
                                      
                                      // 显示名称
                                      AuthTextField(
                                        label: '显示名称',
                                        hintText: '您希望显示的昵称',
                                        controller: _displayNameController,
                                        prefixIcon: Icons.badge_outlined,
                                        validator: Validators.displayName,
                                      ),
                                      
                                      const SizedBox(height: 20),
                                      
                                      // 伴侣名称
                                      AuthTextField(
                                        label: '伴侣称呼',
                                        hintText: '您对TA的昵称',
                                        controller: _partnerNameController,
                                        prefixIcon: Icons.favorite_outline,
                                        validator: Validators.partnerName,
                                      ),
                                      
                                      const SizedBox(height: 20),
                                      
                                      // 恋爱开始日期
                                      Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          const Text(
                                            '恋爱开始日期',
                                            style: TextStyle(
                                              fontSize: 14,
                                              fontWeight: FontWeight.w600,
                                              color: Color(0xFF374151),
                                            ),
                                          ),
                                          const SizedBox(height: 8),
                                          GestureDetector(
                                            onTap: _selectDate,
                                            child: Container(
                                              height: 56,
                                              decoration: BoxDecoration(
                                                color: Colors.white,
                                                borderRadius: BorderRadius.circular(12),
                                                border: Border.all(
                                                  color: Colors.grey.shade200,
                                                  width: 1.5,
                                                ),
                                                boxShadow: [
                                                  BoxShadow(
                                                    color: Colors.black.withOpacity(0.05),
                                                    blurRadius: 4,
                                                    offset: const Offset(0, 2),
                                                  ),
                                                ],
                                              ),
                                              child: Row(
                                                children: [
                                                  const SizedBox(width: 16),
                                                  Icon(
                                                    Icons.calendar_today_outlined,
                                                    color: Colors.grey.shade400,
                                                    size: 20,
                                                  ),
                                                  const SizedBox(width: 12),
                                                  Expanded(
                                                    child: Text(
                                                      _relationshipStartDate != null
                                                          ? '${_relationshipStartDate!.year}-${_relationshipStartDate!.month.toString().padLeft(2, '0')}-${_relationshipStartDate!.day.toString().padLeft(2, '0')}'
                                                          : '选择日期（可选）',
                                                      style: TextStyle(
                                                        fontSize: 16,
                                                        color: _relationshipStartDate != null
                                                            ? const Color(0xFF1F2937)
                                                            : Colors.grey.shade400,
                                                      ),
                                                    ),
                                                  ),
                                                  Icon(
                                                    Icons.arrow_drop_down,
                                                    color: Colors.grey.shade400,
                                                  ),
                                                  const SizedBox(width: 8),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                      
                                      const SizedBox(height: 32),
                                      
                                      // 注册按钮
                                      AuthButton(
                                        text: '创建账号',
                                        onPressed: _handleRegister,
                                        isLoading: authProvider.isLoading,
                                      ),
                                      
                                      const SizedBox(height: 24),
                                      
                                      // 登录链接
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                          Text(
                                            '已有账号？',
                                            style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.grey.shade600,
                                            ),
                                          ),
                                          GestureDetector(
                                            onTap: () => Navigator.pop(context),
                                            child: const Text(
                                              ' 立即登录',
                                              style: TextStyle(
                                                fontSize: 14,
                                                color: Color(0xFFFF6B9D),
                                                fontWeight: FontWeight.w600,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                      
                                      const SizedBox(height: 40),
                                    ],
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
        );
      },
    );
  }
}